const { Sequelize, DataTypes, Op } = require('sequelize')
const {server,database,uid,pwd,dialect}=require('./config')

//创建sequelize对象
const sequelize = new Sequelize(database, uid, pwd, {
    host: server,
    dialect
})

//实例化一个模型
function define(model, body) {
    let obj = Object.assign({
        id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true,
            allowNull: false
        }
    }, body, {
        createAt: {
            type: DataTypes.BIGINT,
            allowNull: false
        },
        updateAt: {
            type: DataTypes.BIGINT,
            allowNull: false
        },
        vessions: {
            type: DataTypes.INTEGER,
            allowNull: false
        },
        remarks: {
            type: DataTypes.STRING(500),
            allowNull: true
        }
    })

    let result = sequelize.define(model, obj, {
        freezeTableName: true,
        timestamps: false,
        hooks: {
            beforeValidate: function (mos) {
                let date = Date.now();
                
                if (mos.isNewRecord) {
                    mos.createAt = date;
                    mos.updateAt = date;
                    mos.vessions = 0;
                }
                else {

                    mos.updateAt = date;
                    mos.vessions += 1;
                }
            },
            beforeBulkCreate: (mosArr) => {
                let date = Date.now();
                mosArr.forEach(mos => {

                    if (mos.isNewRecord) {
                        mos.createAt = date;
                        mos.updateAt = date;
                        mos.vessions = 0;
                    }
                    else {
                        mos.updateAt = date,
                            mos.vessions += 1;
                    }
                });
            }
        }
    })
    return result;
}

module.exports = { define, sequelize, Op }